using NUnit.Framework;
using ValidationFramework;
using ValidationFramework.Reflection;

namespace ExampleLibraryCSharp
{
    public class AddCustomRuleWithTypeCacheStrongTypedExample
    {

        #region Example

        public class Person
        {
            private readonly PropertyValidationManager validationManager;

            public Person()
            {
                validationManager = new PropertyValidationManager(this);
            }

            public string Name
            {
                get;
                set;
            }



            public static void CheckIsNotEmpty(object sender, CustomValidationEventArgs e)
            {
                var name = (string)e.TargetMemberValue;
                if (string.IsNullOrEmpty(name))
                {
                    e.IsValid = false;
                }
                else
                {
                    e.IsValid = true;
                }
            }

            public bool Validate()
            {
                // Use TryValidateProperty in case rules have not yet been applied
                validationManager.TryValidate(() => Name);
                return validationManager.IsValid;
            }
        }
            [TestFixture]
            public class ExampleUsage
            {
                [Test]
                public void RunAddCustomPropertyValidation()
                {
                    var person = new Person();
                    var typeDescriptor = TypeCache.GetType<Person>();
                    var propertyDescriptor =
                        typeDescriptor.GetOrCreatePropertyDescriptor(() => person.Name);
                    var rule = new CustomRule("Name cannot be empty.", false,
                        Person.CheckIsNotEmpty, "Name cannot be empty.");
                    propertyDescriptor.Rules.Add(rule, null);

                    Assert.IsFalse(person.Validate());
                    person.Name = "John";
                    Assert.IsTrue(person.Validate());
                }
            }
        #endregion
    }
}